package db

import (
	"gorm.io/driver/sqlite"
	"os"
	"pm/config"
	"pm/model"
	"gorm.io/gorm"
	"sync"
)


var dbOnce sync.Once
var db *gorm.DB


func NewDb ()*gorm.DB{
	dbOnce.Do(func(){
		_, err := os.Stat(config.ConfigData.DbPath)
		if os.IsNotExist(err) {
			err := os.MkdirAll(config.ConfigData.DbPath, 0755)
			if err != nil {
				panic(err)
			}
		}
		db, err = gorm.Open(sqlite.Open(config.ConfigData.DbPath+"/data.db"),  &gorm.Config{})
		if err != nil {
			panic(err)
		}
		db.AutoMigrate(
			&model.PackageCurrent{},
			&model.Client{},
			&model.PackageHistory{},
			&model.User{},
			&model.UserToken{},
			&model.Package{},
		)
	})
	return db
}






